﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ApplicationServer.Caching;

public class CacheHelper
{
    private static DataCache _cache;
    private string _cacheName;

    public CacheHelper(string cacheName)
    {
        _cacheName = cacheName;
        _cache = GetCache(_cacheName);
    }

    private static DataCache GetCache(string cacheName)
    {
        //Reads settings from web.config
        DataCacheFactory factory = new DataCacheFactory();

        DataCache cache = factory.GetCache(cacheName);
        
        return factory.GetCache(cacheName);

    }

    public object GetFromCache(string key)
    {
        return _cache.Get(key);
    }

    public IList<KeyValuePair<string, object>> GetAllObjectsInRegion(string region)
    {
        try
        {
            return _cache.GetObjectsInRegion(region).ToList();
        }
        catch { return null; }
    }

    public IList<KeyValuePair<string, object>> GetObjectsByTag(string region,string tag)
    {
        try
        {
            return _cache.GetObjectsByTag(new DataCacheTag(tag.ToLower()), region).ToList();
        }
        catch { return null; }
    }

    public void PutInCache(string key, object value)
    {
        
        _cache.Put(key, value);
    }

    public void CreateRegion(string region)
    {
        try
        {
            _cache.CreateRegion(region);
        }
        catch (DataCacheException ex)
        {
            if (ex.ErrorCode != DataCacheErrorCode.RegionAlreadyExists)
                throw;
        }
    }
    public void PutInCache(string key, object value, string region)
    {
        _cache.Put(key, value, region);
    }

    public void PutInCache(string key, object value, string region, string tags)
    {

        List<DataCacheTag> itemTags = new List<DataCacheTag>();

        foreach (var t in tags.Split(',').ToList())
            itemTags.Add(new DataCacheTag(t.ToLower()));

        _cache.Put(key, value, itemTags , region);

    }

}
